package com.wsm.common.utils;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class HttpClientUtil {
	private static Logger logger = LoggerFactory
			.getLogger(HttpClientUtil.class);

	public String doHttpPost(Map<String, String> param) {
		LayeredConnectionSocketFactory sslsf = null;
		try {
			sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		Registry<ConnectionSocketFactory> socketFactoryRegistry = 
				RegistryBuilder.<ConnectionSocketFactory>create()
				.register("https", sslsf)
				.register("http", new PlainConnectionSocketFactory())
				.build();
		PoolingHttpClientConnectionManager cm = 
				new PoolingHttpClientConnectionManager(socketFactoryRegistry);
		cm.setMaxTotal(200);
		cm.setDefaultMaxPerRoute(20);
		CloseableHttpClient httpClient = 
				HttpClients.custom().setConnectionManager(cm).build();
		
		logger.info("http 请求入参>>>>" + param.toString());
		String result = null;
		HttpPost httpPost = null;
		HttpResponse response = null;
		String url = param.get("url");
		try {
			//logger.info("请求系统url：" + url);
			httpPost = new HttpPost(url);
			//设置参数
			List<org.apache.http.NameValuePair> list = 
					new ArrayList<org.apache.http.NameValuePair>();
			Iterator<Entry<String, String>> iterator = param.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<String, String> elem = (Entry<String, String>)iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
			//logger.info("回调业务系统参数：" + list.toString());
			if(list.size()>0){
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
				httpPost.setEntity(entity);
			}
			response = httpClient.execute(httpPost);
			if(null != response){
				HttpEntity resEntity = response.getEntity();
				InputStream in = resEntity.getContent();
	            result = IOUtils.toString(in, "UTF-8");
	            in.close();
				if(null!=result && !"".equals(result)){
					//JSONObject json = JSONObject.parseObject(result);
					//logger.info("业务系统回调接口返回数据：" + json.toJSONString());
                    logger.info("业务系统回调接口返回数据：" + result.replace("{\"", "\n{\""));
				}else{
					logger.info("业务系统回调接口业务异常" + result);
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("调用接口业务异常：", e);
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			logger.error("调用接口业务异常：", e);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("调用接口业务异常：", e);
			e.printStackTrace();
		} finally {
			 httpPost.abort();
		}
		
		return result;
	}
	
	public String doHttpGet(Map<String, String> param) {  
        String result = "";  
        BufferedReader in = null;  
        try {
        	//请求参数包装
        	StringBuffer urlNameString = new StringBuffer();
        	urlNameString.append(param.get("url")).append("?");
            logger.info("get请求入参>>>{}",param.toString()); 
            for(String key: param.keySet()) {
            	if("url" != key) {
            		urlNameString.append(key).append("=").append(param.get(key)).append("&");
            	}
            }
            URL realUrl = new URL(urlNameString.substring(0, urlNameString.length()-1));  
            // 打开和URL之间的连接  
            URLConnection connection = realUrl.openConnection();  
            // 设置通用的请求属性  
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("user-agent",  
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
            // 建立实际的连接  
            connection.connect();  
            // 获取所有响应头字段  
            Map<String, List<String>> map = connection.getHeaderFields();  
            // 遍历所有的响应头字段  
            for (String key : map.keySet()) {  
                System.out.println(key + "--->" + map.get(key));  
            }  
            // 定义 BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(  
                    connection.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            logger.error("发送GET请求出现异常:" + e);  
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (Exception e2) {
            	logger.error("接口调用业务异常：", e2);
                e2.printStackTrace();  
            }  
        }  
        return result;  
    }  
	
	public void doPost (String address, Object data){ 
	    try { 
            //创建连接 
            URL url = new URL(address); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
            connection.setDoOutput(true); 
            connection.setDoInput(true); 
            connection.setRequestMethod("POST"); 
            connection.setUseCaches(false); 
            connection.setInstanceFollowRedirects(true); 
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
            connection.connect(); 
            //POST请求 
            DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 
            out.write(data.toString().getBytes("UTF-8"));
            out.flush(); 
            out.close(); 
            //读取响应 
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
            String lines; 
            StringBuffer sb = new StringBuffer(""); 
            while ((lines = reader.readLine()) != null) { 
                lines = new String(lines.getBytes(), "utf-8"); 
                sb.append(lines); 
            } 
            System.out.println(sb); 
            reader.close(); 
            // 断开连接 
            connection.disconnect(); 
        } catch (MalformedURLException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (UnsupportedEncodingException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
	}
	
}
